package cn.fl.repay.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.fl.repay.constant.InsCstRepayLogConstant;
import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;

import cn.fl.repay.condition.InsCstRepayLogQueryCondition;
import cn.fl.repay.dto.InsCstRepayLogDTO;
import cn.fl.repay.service.IInsCstRepayLogService;
import cn.fl.repay.vo.InsCstRepayLogVO;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;

import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;

/**
 * @Description: 资管客户还款记录表 控制层
 */
@Controller
@RequestMapping("/repay/insCstRepayLog")
public class InsCstRepayLogController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(InsCstRepayLogController.class);

	/**
	 * InsCstRepayLog 服务层BEAN
	 */
	@Autowired
	private IInsCstRepayLogService insCstRepayLogService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载InsCstRepayLog列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("repay/insCstRepayLog/insCstRepayLogList");

		//还款类型
		List<KeyValueVO> payTypCdList = this.insCstRepayLogService.getKVList(InsCstRepayLogConstant.CODE_REPAY_TYP_CD);
		mav.addObject("payTypCdList", JSON.toJSONString(payTypCdList));
		//资管机构
		List<KeyValueVO> insCdList = this.insCstRepayLogService.getKVList(InsCstRepayLogConstant.CODE_INS_ORG_CD);
		mav.addObject("insCdList", JSON.toJSONString(insCdList));

		return mav;
	}
	
	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载InsCstRepayLog Add页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("repay/insCstRepayLog/insCstRepayLogModify");
		this.prepare(request,mav);
		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载InsCstRepayLog Modify页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("repay/insCstRepayLog/insCstRepayLogModify");
		this.prepare(request,mav);
		
		String id=request.getParameter("id");
		InsCstRepayLogVO insCstRepayLogVO = this.insCstRepayLogService.selectById(Long.valueOf(id));
        mav.addObject("insCstRepayLogVO", insCstRepayLogVO);
		return mav;
	}
	
	//加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request,ModelAndView mav){
    	
    }

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initInsCstRepayLogList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		InsCstRepayLogQueryCondition qc = new InsCstRepayLogQueryCondition();
		String lsCntNo = request.getParameter("lsCntNo");
		if (StringUtils.isNotEmpty(lsCntNo)) {
			qc.setLsCntNo(lsCntNo);
		}
		String insBizNo = request.getParameter("insBizNo");
		if (StringUtils.isNotEmpty(insBizNo)) {
			qc.setInsBizNo(insBizNo);
		}
		String paySchNo = request.getParameter("paySchNo");
		if (StringUtils.isNotEmpty(paySchNo)) {
			qc.setPaySchNo(paySchNo);
		}
		String payTypCd = request.getParameter("payTypCd");
		if (StringUtils.isNotEmpty(payTypCd)) {
			qc.setPayTypCd(payTypCd);
		}
		String insCd = request.getParameter("insCd");
		if (StringUtils.isNotEmpty(insCd)) {
			qc.setInsCode(insCd);
		}
		String payTmMin = request.getParameter("payTmMin");
		if (StringUtils.isNotEmpty(payTmMin)) {
			qc.setPayTmMin(DateUtils.formatStringToDate(payTmMin+" 00:00:00",DateUtils.YYYY_MM_DDHHMMSS));
		}
		String payTmMax = request.getParameter("payTmMax");
		if (StringUtils.isNotEmpty(payTmMax)) {
			qc.setPayTmMax(DateUtils.formatStringToDate(payTmMax+" 23:59:59",DateUtils.YYYY_MM_DDHHMMSS));
		}
		page.setCondition(qc);

		BaseLogUtils.info(logger, "initInsCstRepayLogList", "初始化InsCstRepayLog列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		Pager pager = this.insCstRepayLogService.searchListPage(page);
		List<InsCstRepayLogVO> list = (List<InsCstRepayLogVO>) pager.getResultList();
		ListPageVO<InsCstRepayLogVO> listPage = new ListPageVO<InsCstRepayLogVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeInsCstRepayLogByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, PropertiesCacheUtils.getProperty(SysLogConstant.LOG_CMM_DELETE_SUCC));
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(PropertiesCacheUtils.getProperty(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY));
            BaseLogUtils.info(logger, "removeInsCstRepayLogByIds", "删除InsCstRepayLog数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }
		
		try {
			boolean success = this.insCstRepayLogService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(PropertiesCacheUtils.getProperty(SysLogConstant.LOG_CMM_DELETE_FAIL));
				BaseLogUtils.info(logger, "removeInsCstRepayLogByIds", "删除InsCstRepayLog数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeInsCstRepayLogByIds", "删除InsCstRepayLog数据成功,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(PropertiesCacheUtils.getProperty(SysLogConstant.LOG_CMM_SYS_ERROR));
			BaseLogUtils.info(logger, "removeInsCstRepayLogByIds", "删除InsCstRepayLog数据失败,ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(PropertiesCacheUtils.getProperty(SysLogConstant.LOG_CMM_SYS_ERROR));
			BaseLogUtils.error(logger, "removeInsCstRepayLogByIds", "删除InsCstRepayLog数据失败,系统错误.ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getInsCstRepayLogById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getInsCstRepayLogById", "获取InsCstRepayLog数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			InsCstRepayLogVO vo = this.insCstRepayLogService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getInsCstRepayLogById", "获取InsCstRepayLog数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getInsCstRepayLogById", "获取InsCstRepayLog数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getInsCstRepayLogById", "获取InsCstRepayLog数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getInsCstRepayLogById", "获取InsCstRepayLog数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addInsCstRepayLog(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, PropertiesCacheUtils.getProperty(SysLogConstant.LOG_CMM_ADD_SUCC));
		InsCstRepayLogVO entity = null;//获取参数
		try {
			entity = this.getRequestParamForInsCstRepayLog(request);//获取参数
			Long id = this.insCstRepayLogService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "addInsCstRepayLog", "新增InsCstRepayLog数据成功,ID:"+id+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(PropertiesCacheUtils.getProperty(SysLogConstant.LOG_CMM_SYS_ERROR)+ex.getMessage());
			BaseLogUtils.info(logger, "addInsCstRepayLog", "新增InsCstRepayLog数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(PropertiesCacheUtils.getProperty(SysLogConstant.LOG_CMM_SYS_ERROR)+ex.getMessage());
			BaseLogUtils.error(logger, "addInsCstRepayLog", "新增InsCstRepayLog数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyInsCstRepayLog(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,PropertiesCacheUtils.getProperty(SysLogConstant.LOG_CMM_UPDATE_SUCC));
		InsCstRepayLogVO entity = null;
		try {
			entity = this.getRequestParamForInsCstRepayLog(request);
			if(entity.getId()==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(PropertiesCacheUtils.getProperty(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY));
				BaseLogUtils.info(logger, "modifyInsCstRepayLog", "修改InsCstRepayLog信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
				return result;
			}

			boolean success = this.insCstRepayLogService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(PropertiesCacheUtils.getProperty(SysLogConstant.LOG_CMM_UPDATE_FAIL));
				BaseLogUtils.info(logger, "modifyInsCstRepayLog", "修改InsCstRepayLog数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modifyInsCstRepayLog", "修改InsCstRepayLog数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(PropertiesCacheUtils.getProperty(SysLogConstant.LOG_CMM_SYS_ERROR)+ex.getMessage());
			BaseLogUtils.info(logger, "modifyInsCstRepayLog", "修改InsCstRepayLog数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(PropertiesCacheUtils.getProperty(SysLogConstant.LOG_CMM_SYS_ERROR)+ex.getMessage());
			BaseLogUtils.error(logger, "modifyInsCstRepayLog", "修改InsCstRepayLog数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 获取请求参数
	 * @param request 请求
	 * @return 
	 */
	private InsCstRepayLogVO getRequestParamForInsCstRepayLog(HttpServletRequest request) throws BaseException{
		//获取参数
		String id = request.getParameter("id");//主键
		String seqNo = request.getParameter("seqNo");//流水号
		String payTm = request.getParameter("payTm");//交易时间
		String insBizNo = request.getParameter("insBizNo");//资方合同号业务编号
		String insId = request.getParameter("insId");//资管机构ID
		String insCode = request.getParameter("insCode");//资管机构代码
		String insNm = request.getParameter("insNm");//资管机构名称
		String prjId = request.getParameter("prjId");//项目ID
		String lsCntNo = request.getParameter("lsCntNo");//合同号
		String paySchId = request.getParameter("paySchId");//资方支付表ID
		String paySchNo = request.getParameter("paySchNo");//资方支付表号
		String payPd = request.getParameter("payPd");//期数
		String payAmt = request.getParameter("payAmt");//还款金额(分)
		String capAmt = request.getParameter("capAmt");//本金(分)
		String intrAmt = request.getParameter("intrAmt");//利息(分)
		String pntAmt = request.getParameter("pntAmt");//罚息(分)
		String othFeeAmt = request.getParameter("othFeeAmt");//其他费用1(分)
		String othFeeAmt2 = request.getParameter("othFeeAmt2");//其他费用2(分)
		String payTypCd = request.getParameter("payTypCd");//还款类型CAP0069   0.还款 1.客户正常结清 2.客户提前结清 3.逾期强制结清 4.未抵押强制结清 5.我司赎回结清
		String payRem = request.getParameter("payRem");//还款描述信息
		String payAccNm = request.getParameter("payAccNm");//还款户名
		String payAccNo = request.getParameter("payAccNo");//还款账号
		String version = request.getParameter("version");//版本

		//验证参数并赋值
		InsCstRepayLogVO entity = new InsCstRepayLogVO();
 		//entity.setSeqNo(seqNo);//流水号
 		//entity.setPayTm(payTm);//交易时间
 		//entity.setInsBizNo(insBizNo);//资方合同号业务编号
 		//entity.setInsId(insId);//资管机构ID
 		//entity.setInsCode(insCode);//资管机构代码
 		//entity.setInsNm(insNm);//资管机构名称
 		//entity.setPrjId(prjId);//项目ID
 		//entity.setLsCntNo(lsCntNo);//合同号
 		//entity.setPaySchId(paySchId);//资方支付表ID
 		//entity.setPaySchNo(paySchNo);//资方支付表号
 		//entity.setPayPd(payPd);//期数
 		//entity.setPayAmt(payAmt);//还款金额(分)
 		//entity.setCapAmt(capAmt);//本金(分)
 		//entity.setIntrAmt(intrAmt);//利息(分)
 		//entity.setPntAmt(pntAmt);//罚息(分)
 		//entity.setOthFeeAmt(othFeeAmt);//其他费用1(分)
 		//entity.setOthFeeAmt2(othFeeAmt2);//其他费用2(分)
 		//entity.setPayTypCd(payTypCd);//还款类型CAP0069   0.还款 1.客户正常结清 2.客户提前结清 3.逾期强制结清 4.未抵押强制结清 5.我司赎回结清
 		//entity.setPayRem(payRem);//还款描述信息
 		//entity.setPayAccNm(payAccNm);//还款户名
 		//entity.setPayAccNo(payAccNo);//还款账号
 		//entity.setVersion(version);//版本
	
//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

		Date tm=new Date();
		if (StringUtils.isNotBlank(id)) {
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(tm);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		}else{
			entity.setCrtTm(tm);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			//entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
		}
		
		return entity;
	}
}

